package diy_pattern

import (
	"fmt"
	"time"

	"jihe.common/protos/base_server/proto"
	"jihe.common/tool"
)

func (s *Model) Create(in *proto.BaseDiyPattern) (ret *proto.BaseNull, err error) {
	ret = new(proto.BaseNull)
	in.Id = fmt.Sprintf("%d", tool.GetSnowflakeId())
	sqlStr := fmt.Sprintf("INSERT INTO %s (id, url, uid, source, name)VALUES($1,$2,$3,$4,$5)", s.Name)
	_, err = s.Db.Exec(sqlStr, in.Id, in.Url, in.Uid, in.Source, in.Name)
	if err != nil {
		return
	}
	return
}

func (s *Model) GetList(in *proto.BaseDiyPattern) (ret []*proto.BaseDiyPattern, err error) {
	sqlStr := fmt.Sprintf("SELECT id, url, uid, source, name, created_at, updated_at FROM %s where uid = $1 ORDER BY created_at DESC LIMIT 100", s.Name)
	rows, err := s.Db.Query(sqlStr, in.Uid)
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		item := &proto.BaseDiyPattern{}
		var (
			createdAt *time.Time
			updatedAt *time.Time
		)
		err = rows.Scan(&item.Id, &item.Url, &item.Uid, &item.Source, &item.Name, &createdAt, &updatedAt)
		if err != nil {
			return
		}
		if createdAt != nil {
			item.CreatedAt = createdAt.Format("2006-01-02 15:04:05")
		}
		if updatedAt != nil {
			item.UpdatedAt = updatedAt.Format("2006-01-02 15:04:05")
		}
		ret = append(ret, item)
	}
	return
}
